package com.yubb.framework.handler;

import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import com.yubb.common.constant.ShiroConstants;
import com.yubb.common.utils.ServletUtils;
import com.yubb.common.utils.ShiroUtils;
import com.yubb.common.utils.StringUtils;
import com.yubb.framework.config.properties.TenantFilterProperties;
import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.NullValue;
import net.sf.jsqlparser.expression.StringValue;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;

import javax.annotation.Resource;

/**
 *@Description 实现mybatis-plus租户处理器
 *@Author zhushuyong
 *@Date 2021/6/24 22:34
 *@since:
 *@copyright: 版权所有2021 开源组织 gitee(https://gitee.com/jinzheyi)作者：朱述勇<br/>
 *            GitHub(https://github.com/jinzheyi)作者：朱述勇 。
 */
@Slf4j
@Component
public class YubbTenantLineHandler implements TenantLineHandler {

    @Resource
    private TenantFilterProperties tenantFilterProperties;

    @Override
    public Expression getTenantId() {
        String tenantId = ShiroUtils.getTenantId();
        if (StringUtils.isBlank(tenantId) && StringUtils.isNotNull(RequestContextHolder.getRequestAttributes())) {
            tenantId = (String) ServletUtils.getSession().getAttribute(ShiroConstants.TENANT_ID);
        }
        log.debug("租户id为:{}", tenantId);
        if (StringUtils.isNotBlank(tenantId)) {
            return new StringValue(tenantId);
        }
        return new NullValue();
    }

    /**
     * 设置租户列
     * @return
     */
    @Override
    public String getTenantIdColumn() {
        return tenantFilterProperties.getTenantIdColumn();
    }

    /**
     * 需要过滤的表
     * @param tableName 表名
     * @return
     */
    @Override
    public boolean ignoreTable(String tableName) {
        return tenantFilterProperties.getTableFilter().stream().anyMatch((e) -> e.equalsIgnoreCase(tableName));
    }

}
